package org.monster.boot;

import org.monster.context.core.communicator.DosHeader;
import org.monster.context.util.ScannerUtils;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PipedOutputStream;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

import static java.lang.System.out;

/**
 * Dos发送器<br>
 * 和{@link DosReceiver}类通信的线程类，负责接收命令
 *
 * @author Monster
 */
public class DosSender extends Thread {

    /**
     * dos操作
     */
    public static final String DOS_OPTION = "(1)EnteringWebApp. (2)RemoveWebApp. (3)CompileWebApp. (4)AgainInitServer";
    /**
     * 日志器
     */
    private static final Logger logger = Logger.getLogger(DosHeader.class
            .getName());
    /**
     * dos控制台
     */
    private final Scanner scanner = ScannerUtils.getScanner();
    /**
     * 管道
     * 和{@link DosReceiver}线程通信通道流字段
     */
    private PipedOutputStream pipedOut = new PipedOutputStream();

    /**
     * 默认构造方法
     */
    public DosSender() {
        this.pipedOut = new PipedOutputStream();
    }

    /**
     * 获取管道输出流
     * 获取与{@link DosReceiver}的输出流
     *
     * @return {@link PipedOutputStream} 管道输出流
     */
    public PipedOutputStream getPipedOut() {
        return pipedOut;
    }

    @Override
    public void run() {
        out.println(DOS_OPTION);
        try {
            write();
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 写
     * 读取dos命令写入创建的通道输出流<br>
     * 接收对象 {@link DosReceiver}
     *
     * @throws IOException 输入输出异常
     */
    private void write() throws IOException {
        while (scanner.hasNext()) {
            String dosCommand = scanner.next();
            byte[] buffer = dosCommand.getBytes();
            BufferedOutputStream bos = new BufferedOutputStream(pipedOut);
            bos.write(buffer);
            bos.close();
        }
    }
}